CA65 ?= ca65
LD65 ?= ld65
PYTHON ?= python3
NESDIS ?= ../../_tools/nesdis.py
PASS2 ?= ../../_tools/pass2.py
BYTECODE ?= ../../_tools/bytecode_dis.py

all: reconstructed.nes verify

prg.o: prg.s symbols.inc locals.inc
	$(CA65) -g -o $@ $<

header.o: header.s
	$(CA65) -g -o $@ $<

chr.o: chr.s
	$(CA65) -g -o $@ $<

reconstructed.nes: header.o prg.o chr.o linker.cfg
	$(LD65) -C linker.cfg -m reconstructed.map -Ln reconstructed.lbl -o $@ header.o prg.o chr.o

verify: reconstructed.nes
	cmp reconstructed.nes rom.nes
	@echo "Byte-identical ROM verified."

# Regenerate prg.s from prg.bin. Every --table/--data/--extra-seed flag below is a
# documented classification decision, not a convenience; see the header block of prg.s
# and OVERVIEW.md.
pass1:
	$(PYTHON) $(NESDIS) --prg prg.bin --base 0x8000 --project "MUSCLE (U)" \
	    --out prg.s --locals locals.inc --no-symbols --auto-seed \
	    --table 0x9237:40,0xAC35:3,0x9F2B:16 \
	    --data 0xACBD:12 \
	    --extra-seed 0x8644,0x8653,0x9CAD,0xABF7

# Pass 2: replace the derived Label_XXXX names with the semantic routine names and
# their branch-role suffixes, then apply the zero-page names and rebuild locals.inc.
pass2: pass1
	$(PYTHON) $(PASS2) derive prg.s routine_names.tsv label_names.tsv
	$(PYTHON) $(PASS2) apply prg.s label_names.tsv
	$(PYTHON) $(PASS2) apply prg.s zero_page_ranges.tsv
	$(PYTHON) $(PASS2) apply prg.s zero_page_names.tsv
	$(PYTHON) $(PASS2) reflow prg.s
	$(PYTHON) $(PASS2) describe prg.s routine_purposes.tsv
	$(PYTHON) $(PASS2) structure prg.s data_regions.tsv
	$(PYTHON) $(PASS2) locals prg.s zero_page_names.tsv locals.inc zero_page_ranges.tsv

# Pass 3: apply the hardware register names, then decode the bytecode VM
# programs into a readable token listing above each program's unchanged .byte
# data.  Bytecode_dis.py only inserts comment lines; the .byte data it reads
# is copied through verbatim.
#
# The register names are applied here rather than at Pass 1 because this
# project's committed prg.s was produced that way: nesdis.py --no-symbols
# keeps the operands numeric and apply_symbols.py substitutes them in place,
# which is what the committed audit-comment columns reflect.  A project
# started today lets nesdis.py name the registers at Pass 1 instead
# (--symbols, the default) and does not need this step.
pass3: pass2
	$(PYTHON) ../../_tools/apply_symbols.py . --write
	$(PYTHON) $(BYTECODE) prg.bin prg.s

regen: pass3

clean:
	rm -f *.o reconstructed.nes reconstructed_prg.bin reconstructed.map reconstructed.lbl

.PHONY: all verify clean regen pass1 pass2 pass3